import os
import subprocess
import sys

# 添加oj_judger到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from judger import create_judger
from security import SecurityManager

def get_python_program():
    """获取Python示例程序路径"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(current_dir, 'addition.py')


def demo_judger():
    """演示判断器的使用"""
    print("=== OJ Judger 演示 ===")
    
    # 获取程序路径
    executable = get_python_program()
    
    # 检查程序是否存在
    if not os.path.exists(executable):
        print(f"错误: 找不到示例程序 {executable}")
        return
    
    # 创建判断器实例
    judger = create_judger(time_limit=1000, memory_limit=65536)
    
    # 测试用例1: 正确答案
    print("\n--- 测试用例1: 正确答案 ---")
    result = judger.judge(executable, "1 2", "3")
    print(f"输入: 1 2")
    print(f"期望输出: 3")
    print(f"判题结果: {result['result']}")
    print(f"实际输出: {repr(result['stdout'])}")
    print(f"用时: {result['time_used']:.2f}ms")
    
    # 测试用例2: 错误答案
    print("\n--- 测试用例2: 错误答案 ---")
    result = judger.judge(executable, "1 2", "4")
    print(f"输入: 1 2")
    print(f"期望输出: 4")
    print(f"判题结果: {result['result']}")
    print(f"实际输出: {repr(result['stdout'])}")
    
    # 测试用例3: 多行输入输出
    print("\n--- 测试用例3: 多行输入输出 ---")
    result = judger.judge(executable, "10 20\n30 40", "30\n70")
    print(f"输入: 10 20\\n30 40")
    print(f"期望输出: 30\\n70")
    print(f"判题结果: {result['result']}")
    print(f"实际输出: {repr(result['stdout'])}")
    
    # 安全性演示
    print("\n--- 安全性演示 ---")
    with SecurityManager() as security_manager:
        # 验证可执行文件
        is_safe = security_manager.validate_executable(executable)
        print(f"可执行文件安全性检查: {'通过' if is_safe else '未通过'}")
        
        # 在沙箱中运行
        sandboxed_executable = security_manager.create_sandboxed_copy(executable)
        print(f"沙箱中可执行文件路径: {sandboxed_executable}")
        
        # 使用沙箱中的可执行文件进行判题
        result = judger.judge(sandboxed_executable, "5 7", "12")
        print(f"沙箱中判题结果: {result['result']}")


if __name__ == '__main__':
    demo_judger()
